import { FC, useEffect, useState, useRef } from 'react';
import { Drawer, Form, Input } from 'antd';
import { layout } from '@/utils/common';
import ButtonWrap from '@/components/commonComponent/buttonWrap/buttonWrap';
import { useLoading } from '@/hooks/baseHook';
import { message, Select } from 'antd';
import type { ProColumns } from '@ant-design/pro-table';
import { EditableProTable } from '@ant-design/pro-table';
import {
  updatedataset,
  createdataset,
  algorithmtree,
  addDatasetTag,
  putDatasetTag,
  delDatasetTag,
} from '@/api/sr-stms';
import { useRequest } from 'umi';

interface Props extends DrawerProps {
  record: any;
  callback: () => void;
}

type DataSourceType = {
  id?: string;
  index: number;
  tag_name: string;
  note: string;
  uuid: string;
};

const APDrawer: FC<Props> = (props) => {
  const { record, visible, onClose, callback } = props;
  const [form] = Form.useForm();
  const [loading, load] = useLoading();
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  const { data: datasetTreeList } = useRequest(algorithmtree, {
    formatResult: (res: any) => res.data,
  });

  useEffect(() => {
    if (record && visible) {
      form.setFieldsValue(record);
      if (record.dataset_tag?.length > 0) {
        const mapData = record.dataset_tag.map((item: any) => {
          return {
            ...item,
            uuid: (Math.random() * 1000000).toFixed(0),
          };
        });
        setDataSource(mapData);
      }
    }
  }, [record, visible, form]);

  const columns: ProColumns<DataSourceType>[] = [
    // {
    //   title: '序号',
    //   dataIndex: 'index',
    //   formItemProps: (form, { rowIndex }) => {
    //     return {
    //       rules: [{ required: true, message: '此项为必填项' }],
    //     };
    //   },
    // },
    {
      title: '标签',
      dataIndex: 'tag_name',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '备注',
      dataIndex: 'note',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: [{ required: true, message: '此项为必填项' }],
        };
      },
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="edit"
          className="action-edit"
          onClick={() => {
            action?.startEditable?.(record.uuid);
          }}
        >
          编辑
        </a>,
        <a
          key="del"
          className="action-del"
          onClick={async () => {
            setDataSource(
              dataSource.filter((item) => item.uuid !== record.uuid),
            );
            if (!record.id) return;
            await delDatasetTag(record.id)();
            message.success('删除成功！');
            callback();
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const onFinish = async (vals: any) => {
    if (record) {
      // todo 调用接口编辑
      await load(
        updatedataset({
          ...vals,
          id: record.id,
          algorithm_char_name: record.algorithm_char_name,
        }),
      );
      message.success('编辑成功！');
      callback();
      handleClose();
    } else {
      // todo 调用接口新增
      await load(
        createdataset({
          ...vals,
        }),
      );
      message.success('新增成功！');
      callback();
      handleClose();
    }
  };

  const handleClose = () => {
    form.resetFields();
    setDataSource([]);
    setEditableRowKeys([]);
    onClose();
  };

  return (
    <Drawer
      width={600}
      title={record ? '编辑' : '新增'}
      visible={visible}
      onClose={handleClose}
    >
      <Form
        form={form}
        {...layout(4)(19)}
        onFinish={onFinish}
        initialValues={{ enabled: true }}
      >
        <Form.Item
          name="dataset_name"
          label="数据集名称"
          rules={[{ required: true, message: '请输入数据集名称！' }]}
        >
          <Input></Input>
        </Form.Item>
        <Form.Item
          name="algorithm_name"
          label="模型标识名称"
          rules={[{ required: true, message: '请输入模型标识名称！' }]}
        >
          <Select>
            {datasetTreeList?.map((v: any) => {
              return (
                <Select.Option value={v.algorithm_name} key={v.algorithm_name}>
                  {v.algorithm_name}
                </Select.Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item
          name="note"
          label="备注"
          rules={[{ required: true, message: '请输入备注！' }]}
        >
          <Input></Input>
        </Form.Item>
        <ButtonWrap loading={loading} onClose={onClose}></ButtonWrap>
      </Form>
      {record && (
        <EditableProTable<DataSourceType>
          tableStyle={{ padding: 0 }}
          bordered
          rowKey="uuid"
          headerTitle="详情"
          maxLength={5}
          recordCreatorProps={{
            record: () => {
              return {
                uuid: 'add' + (Math.random() * 1000000).toFixed(0),
                index: 0,
                tag_name: '',
                note: '',
              };
            },
          }}
          columns={columns}
          value={dataSource}
          onChange={setDataSource}
          editable={{
            type: 'multiple',
            editableKeys,
            onChange: setEditableRowKeys,
            onlyAddOneLineAlertMessage: '只能同时新增一行',
            actionRender: (row, config, defaultDom) => [
              defaultDom.save,
              defaultDom.cancel,
            ],
            onSave: async (key, dataSource) => {
              console.log(key, dataSource);

              if (dataSource.uuid.includes('add')) {
                // 新增
                await addDatasetTag({
                  dataset_id: record.id,
                  tag_name: dataSource.tag_name,
                  note: dataSource.note,
                });
                message.success('新增成功！');
                callback();
              } else {
                // 编辑
                await putDatasetTag({
                  tag_name: dataSource.tag_name,
                  note: dataSource.note,
                  id: dataSource.id,
                });
                message.success('编辑成功！');
                callback();
              }
            },
          }}
        />
      )}
    </Drawer>
  );
};

export default APDrawer;
